import common.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tmh
 * @date 2024/10/7 15:11
 * @description
 */
public class T105从前序与中序遍历序列构造二叉树 {
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        //遍历中序数组，把中序数组里面的元素放入map里面
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return build(preorder, 0, preorder.length, inorder, 0, inorder.length);
    }

    private TreeNode build(int[] preorder, int preBegin, int preEnd, int[] order, int orderBegin, int orderEnd) {
        //条件判断
        if (preBegin >= preEnd || orderBegin >= orderEnd) {
            return null;
        }
        //从前序数组中获取根节点
        TreeNode root = new TreeNode(preorder[preBegin]);
        //从map里面获取中序数组中根节点的位置
        Integer rootIndex = map.get(preorder[preBegin]);
        //获取左子树的长度
        int lenOfLeft = rootIndex - orderBegin;
        //获取前序数组里面的左右区间
        //左区间
        int preLeftBegin = preBegin + 1;
        int preLeftEnd = preBegin + 1 + lenOfLeft;
        //右区间
        int preRightBegin = preBegin + 1 + lenOfLeft;
        int preRightEnd = preEnd;
        //获取中序数组里面的左右区间
        //左区间
        int inorderLeftBegin = orderBegin;
        int inorderLeftEnd = rootIndex;
        //右区间
        int inorderRightBegin = rootIndex + 1;
        int inorderRightEnd = orderEnd;
        //注意：上面是可以直接利用rootIndex来当作区间的
        root.left = build(preorder, preLeftBegin, preLeftEnd, order, inorderLeftBegin, inorderLeftEnd);
        root.right = build(preorder, preRightBegin, preRightEnd, order, inorderRightBegin, inorderRightEnd);
        return root;
    }
}
